package com.article.controller;


import com.article.entity.dto.UserDto;
import com.article.entity.pojo.User;
import com.article.result.Result;
import com.article.service.UserService;
import com.article.utils.JwtUtil;
import com.article.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    // 登录功能
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        log.info("用户登录，用户名：{}，密码：{}", user.getUsername(), user.getPassword());
        User res = userService.login(user);
        if (res != null) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", res.getId());
            claims.put("username", res.getUsername());
            String token = JwtUtil.genToken(claims);
            return Result.success(token);
        } else {
            return Result.error("用户名或密码错误");
        }
    }

    // 注册功能
    @PostMapping("/register")
    public Result register(@RequestBody UserDto userDto) {
        log.info("用户注册，用户名：{}，密码：{}，密码2：｛｝", userDto.getUsername(), userDto.getPassword(), userDto.getPassword1());
        int i = userService.register(userDto);
        if (i == 1) {
            return Result.success();
        } else {
            return Result.error("注册失败");
        }
    }

    // 获取用户信息
    @GetMapping("/info")
    public Result getUserInfo() {

        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");

        log.info("获取用户信息，{}", id);
        User user = userService.getUserInfo(id);
        return Result.success(user);
    }

    // 退出登录
    @PostMapping("/logout")
    public Result logout() {
        log.info("用户退出登录");
        ThreadLocalUtil.remove();
        return Result.success();
    }

}


